package servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Response的应用，读取服务器中的文件以流的方式写到response的输出流中，
 * 根据设置的响应类型，可实现文件下载或显示等功能
 */
@WebServlet("/response.view")
public class ResponseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ResponseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置ContentType为image/jpg，则会在页面中显示图片
		response.setContentType("image/jpg");
		//设置Header为"content-disposition", "attachment;filename=ferrari.jpg"，则会实现下载该图片。
		//response.setHeader("content-disposition", "attachment;filename=ferrari.jpg");
		ServletOutputStream outputStream = response.getOutputStream();
		String filePath = request.getServletContext().getRealPath("/WEB-INF/download/ferrari.jpg");
		FileInputStream fis = new FileInputStream(new File(filePath));
		byte[] buff = new byte[1024];
		while(fis.read(buff)!=-1){
			outputStream.write(buff);
		}
		fis.close();
		outputStream.close();
		
		
	}

}
